package cn.sirun.com.fca.personal.center.presenter.impl;

import com.tencent.cloud.iov.kernel.constant.StatusCode;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.flow.presenter.impl.BaseDisposablePresenter;

import cn.sirun.com.fca.account.observer.ConvertExceptionObserver;
import cn.sirun.com.fca.personal.center.constant.PersonalCenterActionConst;
import cn.sirun.com.fca.personal.center.model.request.SubmitEmergencyInfoRequest;
import cn.sirun.com.fca.personal.center.model.service.PersonalInfoManager;
import cn.sirun.com.fca.personal.center.presenter.IChangeEmergencyContactPresenter;
import cn.sirun.com.fca.personal.center.repo.ProfileRepository;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ChangeEmergencyContactPresenter extends BaseDisposablePresenter
        implements IChangeEmergencyContactPresenter {

    @Override
    public void submitEmergencyInfo(final SubmitEmergencyInfoRequest request) {
        ProfileRepository.getInstance().submitEmergencyInfo(request)
                .subscribeOn(Schedulers.io())
                .compose(this.<BaseResponse<Void>>getDisposeTransformer())
                .doOnNext(new Consumer<BaseResponse<Void>>() {
                    @Override
                    public void accept(BaseResponse<Void> response) throws Exception {
                        if (StatusCode.SUCCESS == response.getCode()) {
                            PersonalInfoManager.getInstance().updateEmergencyInfo(
                                    request.getName(), request.getPhone()
                            );
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ConvertExceptionObserver<Void>() {
                    @Override
                    public void onNext(BaseResponse<Void> response) {
                        super.onNext(response);
                        onAction(PersonalCenterActionConst.ACTION_SUBMIT_EMERGENCY_INFO, response);
                    }
                });
    }
}
